package com.qing.study.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.qing.study.comm.Result;
import com.qing.study.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String accessToken = request.getHeader("Authorization"); // 假设token在Authorization头中

        if (accessToken == null || !accessToken.startsWith("Bearer ")) {
            // Token不存在或格式错误
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json");
            // response.getWriter().write("{\"error\":\"Unauthorized\",\"message\":\"Invalid or missing token\"}");
            response.getWriter().write(JSONObject.toJSONString(Result.error(401, "Invalid or missing token")));
            return false;
        }

        accessToken = accessToken.substring(7); // 去掉"Bearer "前缀

        if (!tokenService.isValidToken(accessToken)) {
            // Token无效或已过期
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json");
            // response.getWriter().write("{\"error\":\"Unauthorized\",\"message\":\"Token is invalid or expired\"}");
            response.getWriter().write(JSONObject.toJSONString(Result.error(401, "Token is invalid or expired")));
            return false;
        }

        // Token有效，可以继续处理请求
        return true;
    }
}
